package org.zero.db;

import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.zero.exception.UtilException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;

/**
 * 数据库连接工具类
 * 依赖：
 * 1、数据源
 * 2、TransactionManager.java 事务管理工具类
 *
 * @author Zero (cnzeropro@qq.com)
 * @date 2021/8/10 11:49
 */
@UtilityClass
public class ConnectionUtil {
    private static final DataSource DATA_SOURCE;

    static {
        try {
            Dbcp2Enhancer dbcp2Enhancer = new Dbcp2Enhancer("dbcp.properties");
            DATA_SOURCE = dbcp2Enhancer.getDataSource();
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static void setTransactionManager() {
        TransactionManager.setConnection(getConnection());
    }

    public static void removeTransactionManager() {
        closeConnection(TransactionManager.getConnection());
        TransactionManager.remove();
    }

    @SneakyThrows
    public static void destroyDataSource() {
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            DriverManager.deregisterDriver(drivers.nextElement());
        }
        AbandonedConnectionCleanupThread.checkedShutdown();
    }

    public static DataSource getDataSource() {
        if (DATA_SOURCE == null) {
            throw new UtilException("DataSource is null!!!");
        }
        return DATA_SOURCE;
    }

    @SneakyThrows
    public static Connection getConnection() {
        return getDataSource().getConnection();
    }

    @SneakyThrows
    public static void closeConnection(Connection connection) {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
    }
}
